﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;

using Moe.ECamel.Common.Entities;

namespace Moe.ECamel.Server.BL
{
	public class CustomerBL : ECamelBL
	{
		/// <summary>
		/// Default constructor for business logic component.
		/// </summary>
		/// <param name="dataContext">Data context to be used by this component's operations.</param>
		public CustomerBL(ECamelDataContext dataContext)
			: base(dataContext)
		{
		}

		public List<Customer> GetCustomersByLibrary(int libraryId)
		{
			// Configure load options:
			DataLoadOptions loadOptions = new DataLoadOptions();
			loadOptions.LoadWith<Customer>(c => c.User);
			//loadOptions.LoadWith<User>(u => u.UserRoles);
			ECamelDataContext adhocDC = new ECamelDataContext(dataContext.Connection);
			adhocDC.ObjectTrackingEnabled = false;
			adhocDC.LoadOptions = loadOptions;

			var query = from c in adhocDC.Customers
						where c.LibraryId == libraryId
						select c;
			return query.ToList();
		}
		public Customer GetCustomerById(int customerId)
		{
			var query = from c in dataContext.Customers
						where c.CustomerId == customerId
						select c;
			return query.SingleOrDefault();
		}
		public Customer GetCustomerByUserId(int userId)
		{
			// Configure load options:
			DataLoadOptions loadOptions = new DataLoadOptions();
			loadOptions.LoadWith<Customer>(c => c.User);
			loadOptions.LoadWith<Customer>(c => c.Library);
			ECamelDataContext adhocDC = new ECamelDataContext(dataContext.Connection);
			adhocDC.ObjectTrackingEnabled = false;
			adhocDC.LoadOptions = loadOptions;

			var query = from c in adhocDC.Customers
						where c.UserId == userId
						select c;
			return query.SingleOrDefault();
		}

		public ECamelError CreateCustomer(Customer customer)
		{
			// Validate customer:
			ECamelError validationError = ValidateCustomer(customer);
			if (validationError != null)
				return validationError;

			// Insert:
			dataContext.Customers.InsertOnSubmit(customer);

			return null;
		}
		public ECamelError UpdateCustomer(Customer customer)
		{
			// Validate:
			ECamelError validationError = ValidateCustomer(customer);
			if (validationError != null)
				return validationError;

			// Update:
			dataContext.Customers.Attach(customer, true);

			return null;
		}

		private static ECamelError ValidateCustomer(Customer customer)
		{
			// Validate customer:
			ECamelError error = customer.Validate();
			if (error != null)
				return error;

			return null;
		}
	}
}